// pages/home/workContent/workContent.js
const util = require('../../../utils/util.js');
const dayjs = require('../../../utils/lib/dayjs.min.js');
const OPENID = wx.getStorageSync('userOpenid').OPENID;
const db = wx.cloud.database();
Page({

  /**
   * 页面的初始数据
   */
  // 110.929277,21.685018
  data: {
    isPopupWindow: false,
    _id: "",
    IdApplyWorkData: 0,
    deadlineDate: null,
    latitude: 21.685018,
    longitude: 110.929277,
    markers: [{
      id: 1,
      latitude: 21.685018,
      longitude: 110.929277,
      name: 'T.I.T 创意园'
    }],
    covers: [{
      latitude: 21.685018,
      longitude: 110.929277,
      iconPath: '/image/location.png'
    }, {
      latitude: 21.685018,
      longitude: 110.929277,
      iconPath: '/image/location.png'
    }],

    merchants: {
      "openid": "",
      "name": "黄先生",
      "company": "茂名家教公司",
      "workPosition": "招聘顾问"
    },
    workData: {
      title: "示例",
      tag: [
        { tagData: "高薪", tagColor: "green" },
        { tagData: "热门", tagColor: "red" },
        { tagData: "待遇好", tagColor: "blue" },
        { tagData: "地带繁荣", tagColor: "yellow" }
      ],
      wage: '10000 - 15000 人民币/月',
      deadlineDate: '2022/05/04',
      workInformation: "【岗位介绍】（1）主持或参与游戏大数据及数据分析的前沿研究工作，通过发表论文等形式，引领行业发展（2）主持及参与游戏数据分析的新方法的构建、流程革新、工具研发及转化落地（3）对海量游戏数据中产生富有挑战性的命题进行分析、解释、归纳、预测等，直接服务于公司决策层和顶级产品",
      workrequirements: "（1）硕士以上学历，计算机、统计学、数据科学专业优先（2）多年工作经验，游戏行业优先（3）精通前沿的数据处理工具，能够指导团队的技术体系建设（4）具有扎实的数理统计知识，能通过数据识别业务问题或潜在风险，找到业务突破点，推动产品创新（5）有领导、解决高复杂度大中型项目的经验"
    }

  },

  openPopupWindow: function () {
    this.setData({
      isPopupWindow: true
    });
  },

  closePopupWindow: function () {
    this.setData({
      isPopupWindow: false
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var workDataId
    const eventChannel = this.getOpenerEventChannel()
    eventChannel.on('workDataId', function (res) {
      workDataId = res.data;
    })
    //TODO:获得数据 workData
    db.collection('workData').doc(workDataId)
      .get({
        success: res => {
          console.log(res.data)
          // console.log("res.data.workData.deadlineDate" + res.data.deadlineDate)

          this.setData({
            _id:workDataId,
            workData: res.data,
            IdApplyWorkData: res.data.IdApplyWorkData,
            deadlineDate: dayjs(res.data.deadlineDate).format("YYYY-MM-DD")
          })
        },
      })
  },

  // onReady: function (e) {
  //   this.mapCtx = wx.createMapContext('myMap')
  // },

  onApply: function (e) {
    const tableName = 'applyWorkData'
    const idWorkData = this.data._id
    const IdApplyWorkData = this.data.IdApplyWorkData
    // const IdApplyWorkData = '18ed09686174035d0180981d6d051b9a'
    var applyList = []
    var isApplyed = false

    db.collection(tableName).doc(IdApplyWorkData).get({
      success: res => {
        applyList = res.data.applyList
        console.log("isApplyed: " + isApplyed)

        for (var i = 0; i < applyList.length; i++) {
          if (applyList[i].openIdApplyer == OPENID) {
            isApplyed = true
          }
        }

        if (!isApplyed) {
          applyList.push({
            openIdApplyer: OPENID,
            stateApplyer: 1
          })

          db.collection(tableName).doc(IdApplyWorkData).update({
            data: {
              applyList: applyList
            },
            success: res => {
              console.log(res)
            }
          })

          db.collection('applyerApplyData').where({
            _openid: OPENID
          })
            .get({
              success: res => {
                var applyList2
                var idApplyList

                idApplyList = res.data[0]._id
                applyList2 = res.data[0].applyList

                applyList2.push({
                  idApplyWorkData: IdApplyWorkData,
                  idWorkData: idWorkData,
                  stateApply: 1
                })

                db.collection('applyerApplyData').doc(idApplyList).update({
                  data: {
                    applyList: applyList2
                  },
                  success: res => {
                    var number = this.data.workData.number
                    // 人数未满
                    if(number.applications+1 != number.restrictions){
                      db.collection('workData').doc(this.data._id).update({
                        // data 传入需要局部更新的数据
                        data: {
                          number: {
                            applications : number.applications+1,
                            restrictions : number.restrictions
                          }
                        },
                        success: function(res) {
                          console.log(res.data)
                        }
                      })
                    }else{// 人数己满
                      db.collection('workData').doc(this.data._id).update({
                        // data 传入需要局部更新的数据
                        data: {
                          number: {
                            applications : number.applications+1,
                            restrictions : number.restrictions
                          },
                          state:2
                        },
                        success: function(res) {
                          console.log(res.data)
                        }
                      })
                    }

                    wx.showToast({
                      title: "申请成功",
                      icon: 'success',
                      duration: 2000
                    })
                    console.log(res)
                  }
                })

              }
            })


        } else {
          wx.showToast({
            title: "你己经申请过了",
            icon: 'error',
            duration: 2000
          })
        }

      }
    })

    this.setData({
      isPopupWindow: false
    });
    // 注意数据库权限问题
    // res.data[0]
  },
})